const obj = {
    // 字符串默认值
    StrDef: function (str) {
        if (typeof str === "undefined") {
            return "";
        } else if (str == null) {
            return "";
        } else {
            return str;
        }
    },

    // 数值默认值
    NumDef: function (num) {
        if (typeof num === "undefined") {
            return 0;
        }else if (isNaN(num)){
            return 0;
        } else {
            return num;
        }
    },

    // 判断是否是日期
    IsDate: function (str) {
        return ! isNaN(Date.parse(str));
    },

    // 两日期相差天数
    DiffDay: function (date1, date2){
        let date1_num = new Date(date1.replace(/-/g, "/")); // 将起始日期字符串转换为日期对象
        let date2_num = new Date(date2.replace(/-/g, "/")); // 将结束日期字符串转换为日期对象
        let day = parseInt((date2_num.getTime() - date1_num.getTime()) / (1000 * 60 * 60 * 24)); return day;
    },

    // 获取当前日期 yyyy-mm-dd
    GetDate: function (){
        var date= new Date();
        const year = date.getFullYear().toString().padStart(2, '0');
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        var currDate = year + '-' + month + '-' + day;
        return currDate;
    },

    // 获取时间 hh:nn:ss
    GetTime: function (){
        var date= new Date();
        const hour = date.getHours().toString().padStart(2, '0');
        const minute = date.getMinutes().toString().padStart(2, '0');
        const second = date.getSeconds().toString().padStart(2, '0');
        return hour +":"+ minute +":"+ second;
    },

    // 获取时间 yyyy-mm-dd hh:nn:ss
    GetDateTime: function (){
        return this.GetDate() +" "+ this.GetTime();
    },

    // 获取时间总秒数（timeStr：hh:nn:ss）
    GetHourTimer: function (timeStr){
        let retNum = -1;
        if (timeStr == ""){
            let date= new Date();
            const hour = date.getHours();
            const minute = date.getMinutes();
            const second = date.getSeconds();
            retNum = hour*3600 + minute*60 + second;
        }else{
            let timeArr = timeStr.split(':');
            retNum = parseInt(timeArr[0])*3600 + parseInt(timeArr[1])*60 + parseInt(timeArr[2]);
        }
        return retNum;
    },

    // 获取小时分钟 hh:nn
    GetTimeMin: function (){
        var date= new Date();
        const hour = date.getHours().toString().padStart(2, '0');
        const minute = date.getMinutes().toString().padStart(2, '0');
        const second = date.getSeconds().toString().padStart(2, '0');
        return hour +":"+ minute;
    },

    // 增加小时分钟格式的分钟数 hh:nn
    AddTimeMin(str, num) {
        let timeArr = str.split(":");
        let hour = parseInt(timeArr[0]);
        let min = parseInt(timeArr[1]) + num;
        if (min >= 60){
            diff = parseInt(min / 60);
            hour += diff;
            min -= 60 * diff;
        }
        return hour +":"+ min;
    },

    // 日期时间格式中获取 mm:dd hh:nn
    GetMonthMin: function (datetime){
        if (datetime.length <= 11){ datetime = this.GetDateTime(); }
        return datetime.substr(5,11);
    },

    // 日期添加年数、月数、天数
    GetDateAdd: function (date, addYear, addMonth, addDay){
        let date_ = new Date(date.replace(/-/g, "/"));          // 将日期字符串转换为日期对象
        // console.log(date_);
        if (addYear != 0){
            date_ = new Date(date_.setFullYear(date_.getFullYear() + addYear));  // 加addYear年
        }
        if (addMonth != 0){
            date_ = new Date(date_.setMonth(date_.getMonth() + addMonth));    // 加addMonth月
        }
        if (addDay != 0){
            date_ = new Date(date_.setDate(date_.getDate() + addDay));        // 加addDay天
        }
        // console.log(date_);
        const year = date_.getFullYear().toString().padStart(2, '0');
        const month = (date_.getMonth() + 1).toString().padStart(2, '0');
        const day = date_.getDate().toString().padStart(2, '0');
        var currDate = year + '-' + month + '-' + day;
        return currDate;
    },

    // 时间戳格式化为 日期 或 日期时间
    TimerToTime: function(number, format) {
        var n = number;
        var date = new Date(n);
        var y = date.getFullYear().toString().padStart(2, '0');
        var m = (date.getMonth() + 1).toString().padStart(2, '0');
        var d = date.getDate().toString().padStart(2, '0');
        if (format == "datetime"){
            var h = date.getHours().toString().padStart(2, '0');
            var min = date.getMinutes().toString().padStart(2, '0');
            var s = date.getSeconds().toString().padStart(2, '0');
            return y + '-' + m + '-' + d + ' ' + h + ':' + min + ':' + s;
        }else{
            return y + '-' + m + '-' + d;
        }
    },

    // 秒数格式化为时间 hh:nn:ss 或 nn:ss
    secToTime: function(sec) {
        let hour = 0;
        let min = 0;
        let retStr = "";
        if (sec >= 3600){
            hour = parseInt(sec / 3600);
            sec -= hour * 3600;
            retStr += hour.toString().padStart(2, '0') +":";
        }
        if (sec >= 60){
            min = parseInt(sec / 60);
            sec -= min * 60;
            // retStr += min.toString().padStart(2, '0') +":";
        }
        // retStr += sec.padStart(2, '0');
        retStr += min.toString().padStart(2, '0') +":"+ sec.toString().padStart(2, '0');
        
        return retStr;
    },

    // 警示框并跳转
    AlertHref: function (str, url){
        wx.showModal({
            title: '温馨提示',
            content: str,
            showCancel: false,
            success: (res) => {
                if (res.confirm) {
                    wx.redirectTo({
                        url: url,
                    });
                }
            }
        })
    },

    // 警示框带确定按钮
    AlertTrue: function (title, str){
        wx.showModal({
            title: title,
            content: str,
            showCancel: false,
            success: function(res) {
                if (res.confirm) {
                    console.log('用户点击确定');
                } else if (res.cancel) {
                    console.log('用户点击取消');
                }
                return true;
            },
            fail: function(res) {
                return false;
            }
        });
    },

    // 错误警示框
    AlertErr: function (str){
        wx.showToast({
            title: str,
            icon: 'error',
            duration: 3500
        })
    },

    // 正确警示框
    AlertSucc: function (str){
        wx.showToast({
            title: str,
            icon: 'success',
            duration: 3500
        })
    },

    // 无图标警示框
    AlertNone: function (str){
        wx.showToast({
            title: str,
            icon: 'none',
            duration: 3500
        })
    },

    // 输出log日志并警示框
    ErrLog: function (str, e){
        console.log(str)
        if (typeof e !== "undefined" && e != ''){
            console.error('ErrLog：', e);
            // console.log('ErrLog：',e);
        }
        wx.showToast({
            title: str,
            icon: 'none',
            duration: 3500
            })
    },

    HttpGet: function (url, errType){
        var retArr = {"res": false, "note": '', "data": null}
        console.log("HttpGet:"+ url);
        // 发起网络请求
        return new Promise(function(resolve, reject){
            wx.showLoading({
                "mask": true
              });

            wx.request({
                url: url,
                method: "GET",
                success: (res) => {     // res.data 请求内容集
                    retArr["data"] = res;
                    if (res.statusCode == 200){
                        if (res.data.res){
                            retArr["res"] = true;
                            retArr["note"] = '';
                        }else{
                            retArr["note"] = res.data.note;
                        }
                    }else{
                        retArr["note"] = '获取'+ errType +'状态错误'+ res.statusCode;
                    }
                },
                fail: function(res){ 
                    retArr["note"] = '获取'+ errType +'数据出错';
                    retArr["data"] = res;
                },
                complete: function(res) {
                    resolve( retArr )
                    wx.hideLoading();
                }
            })
        })
    },

    HttpPost: function (paraArr, errType){
        var app = getApp();
        var retArr = {"res": false, "note": '', "data": null}
        var reqUrl = app.globalData.apiUrl;
        if (paraArr.url !== undefined){
            reqUrl = paraArr.url;
        }
        console.log(errType +" HttpPost:"+ reqUrl);
        console.log(paraArr);
        // 发起网络请求
        return new Promise(function(resolve,reject){
            wx.showLoading({
                "mask": true
              });

            wx.request({
                url: reqUrl,
                method: "POST",
                header:{"content-type" :'application/x-www-form-urlencoded'},
                data: paraArr,
                success: (res) => {     // res.data 请求内容集
                    retArr["data"] = res;
                    if (res.statusCode == 200){
                        if (res.data.res){
                            retArr["res"] = true;
                            retArr["note"] = '';
                        }else{
                            retArr["note"] = res.data.note;
                        }
                    }else{
                        retArr["note"] = '获取'+ errType +'状态错误'+ res.statusCode;
                    }
                },
                fail: function(res){ 
                    retArr["note"] = '获取'+ errType +'数据出错';
                    retArr["data"] = res;
                },
                complete: function(res) {
                    resolve( retArr )
                    wx.hideLoading();
                }
            })
        })
    },

    ShareArr: function (str){
        var app = getApp();
        var retArr = {
            action: str,
            updateTime: app.globalData.updateTime,
            siteType: app.globalData.siteType,
            siteId: app.globalData.siteId,
            siteKey: app.globalData.siteKey,
            apiID: app.globalData.siteId,
            appID: app.globalData.siteKey,
            userID: app.globalData.user.id,
            username: app.globalData.user.username,
            nickname: app.globalData.user.nickname,
            openid: app.globalData.user.openid,
            key: app.globalData.user.key,
        }
        return retArr;
    },

    // 获取当前页url
    GetCurrUrl(){  //此方法不带参数
        var pages = getCurrentPages()    //获取加载的页面
        var currentPage = pages[pages.length-1]    //获取当前页面的对象
        var url = currentPage.route 
        return url
    },

    // 获取当前页url+参数
    GetCurrUrlPara(){
        var pages = getCurrentPages()    //获取加载的页面
        var currentPage = pages[pages.length-1]   //获取当前页面的对象
        var url = currentPage.route    //当前页面url
        var options = currentPage.options //如果要获取url中所带的参数可以查看options
        var urlFull = url + '?'
        for(var key in options){
            var value = options[key]
            urlFull += key + '=' + value + '&'
        }
        urlFull = urlFull.substring(0, urlFull.length-1)
        return urlFull
    },
    
    // 打开【设置】页面
    OpenSysPage(e){
        var type_ = e.currentTarget.dataset.type;
        wx.navigateTo({
            url: '../my/sys?type='+ type_,
            fail: function(res) {
                this.ErrLog("跳转失败", res)
            }
        });
    },
    
    // 检查订阅
    CheckDingyue(obj, type, theme, tplid, sendTime, pageUrl, dataObj, dataName){
        if (obj.data[dataName]){
            obj.setData({ [dataName]: true });
            wx.showToast({
                title: '如要取消该订阅提醒，请到【我的】[订阅提醒推送]操作',
                icon: 'none',
                duration: 6000
                });
            return false;
        }
        var that = this;
        wx.requestSubscribeMessage({
            tmplIds: [tplid],
            success: function (res) {
                if (res[tplid] === 'accept'){
                    console.log("订阅成功");
                    that.AlertSucc('订阅提醒成功！');
                    obj.setData({ [dataName]: true });

                    var shareArr = that.ShareArr("dingyueDeal");
                    var paraArr = {
                        type: type,
                        theme: theme,
                        tplid: tplid,
                        pageUrl: pageUrl,
                        sendTime: sendTime,
                        data: JSON.stringify(dataObj),  // JSON.parse(dataObj)字符串转对象
                        state: 0,
                        sign: "123456"
                    };

                    paraArr = Object.assign(shareArr, paraArr);
                    
                    console.log(paraArr);
                    that.HttpPost(paraArr, "新增订阅信息").then(function (retArr) {
                        console.log(retArr);
                        if (! retArr.res){ that.ErrLog(retArr.note);return false; }
                        let apiData = retArr.data.data;
                        var dbArr = apiData.data;

                        that.AlertSucc("订阅提醒成功");   // apiData.note
                    });
                }else{
                    console.log("订阅失败");
                    that.AlertErr({ title: '订阅提醒失败！' });
                    obj.setData({ [dataName]: false });
                }
                console.log(res);
            },
            fail(err) {
                console.log("订阅失败fail");
                that.AlertErr({ title: '订阅提醒失败fail！' });
                console.error(err);
                obj.setData({ [dataName]: false });
            }
        });
    },

    FileUnit: function (fileSize, fixNum, dzStr){
        if (fileSize >= 1073741824){
			fileSize = (fileSize / 1073741824).toFixed(fixNum) + dzStr +'GB';
		} else if (fileSize >= 1048576){
			fileSize = (fileSize / 1048576).toFixed(fixNum) + dzStr +'MB';
		} else if (fileSize >= 1024){
			fileSize = (fileSize / 1024).toFixed(fixNum) + dzStr +'KB';
		} else {
			fileSize = fileSize + dzStr +'字节';
        }
        return fileSize;
    },

    Base64ToImg: function (base64, fileName){
        const imgPath = wx.env.USER_DATA_PATH + "/" + fileName;
        // 如果图片字符串不含要清空的前缀,可以不执行下行代码.
        const imageData = base64.replace(/^data:image\/\w+;base64,/, "");
        const fs = wx.getFileSystemManager();
        try {
          const res = fs.writeFileSync(imgPath, imageData, "base64");
          
          console.log(res)
        } catch(e) {
          console.error(e)
        }
        fs.close();
        return imgPath;
    },
    ToInt(str){
        var retNum = /^\d*$/;
        // retNum.test()用于检测括号里面的数据是否为数字
        if( retNum.test(str) ){
            return parseInt(str);
        }else{
            return 0;
        }
    }
}

module.exports = obj;